//
//  RadioPlayViewController.m
//  lisure0.1
//
//  Created by xalo on 16/4/20.
//  Copyright © 2016年 Mr.wangYongxu. All rights reserved.
//

#import "RadioPlayViewController.h"
#import "PlayInfoModel.h"
#import "authOrUsrModel.h"
#import "RadioListTableViewCell.h"
#import "FMDetailModel.h"

@interface RadioPlayViewController ()<UITableViewDelegate,UITableViewDataSource,PlayManagerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *coverimg;
@property (weak, nonatomic) IBOutlet UILabel *titleLable;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property (weak, nonatomic) IBOutlet UISlider *downLoadPrograss;
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (weak, nonatomic) IBOutlet UIPageControl *pagecontroller;//小白点
@property (weak, nonatomic) IBOutlet UIButton *playBtn;//播放暂停按钮
@property (weak, nonatomic) IBOutlet UIButton *nextBtn;//下一曲
@property (weak, nonatomic) IBOutlet UIButton *perBtn;//上一曲
@property (weak, nonatomic) IBOutlet UILabel *timeLable;//时间的显示框

@property (retain, nonatomic) NSString* currentTingId;//记录当前播放的id
@property (retain, nonatomic) NSTimer* animatedTimer;//控制播放的定时器

@end

@implementation RadioPlayViewController

//为保证每一次进来都是同一播放源，即时切出界面，依旧保持状态
+(instancetype)shareRadioPlay{

    static RadioPlayViewController* handle= nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        handle = [[UIStoryboard storyboardWithName:@"Radio" bundle:nil] instantiateViewControllerWithIdentifier:@"RadioPlayViewController"];
    });
    return  handle;
}



#pragma mark - 视图生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view layoutIfNeeded];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self setVIews];
    self.currentTingId = @"";
    self.pagecontroller.currentPage = 1;
    [self.scrollView setContentOffset:CGPointMake(kViewWidth, 0)];
    [PlayManager shareManager].delegate = self;
    [self.scrollView setUserInteractionEnabled:YES];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//视图将要出现
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    if ([self.currentTingId isEqualToString:self.model.tingid]) {
        return;
    }
    [self loadDataOfPlayInfo];
    [self playRadio];

}

#pragma mark - 音乐播放
- (IBAction)downMusic:(id)sender {

    DownLoadManager* manager = [DownLoadManager defaultManager];
    if (![manager downLoadWithmodel:self.model]) {
       DownLoadTool* downLoad = [manager addDownLoadWithPlayInfoModel:self.model];
        [[DownLoadViewController sharedDownLoad].downLoadListArr addObject:downLoad];
    }

}

//播放音乐
-(void)playRadio{
    _isPlay = YES;
    [self startTimer];
    self.currentTingId =self.model.tingid;
    [[PlayManager shareManager] preoareToPlayRadiowithUrl:[self.radiolist[self.index] musicUrl]];
    [[PlayManager shareManager] playRadio];
    [self.playBtn setTitle:@"暂停" forState:UIControlStateNormal];
}

//自动旋转
-(void)animationOfImage{

    self.coverimg.transform = CGAffineTransformRotate(self.coverimg.transform, M_PI/360);
}

-(void)startTimer{

    if (self.animatedTimer) {
        return;
    }
    self.animatedTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(animationOfImage) userInfo:nil repeats:YES];
//    [self.animatedTimer fire];
}

-(void)closeTimer{

    [self.animatedTimer invalidate];
    self.animatedTimer = nil;
}
#pragma mark - 点击事件

- (IBAction)changeProgress:(UISlider *)sender {
    [[PlayManager shareManager] bySliderValueToPlayRadio:self.downLoadPrograss.value];
}


//next歌曲
- (IBAction)nextRadio:(id)sender {

    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        self.index = self.index == self.radiolist.count - 1?0:self.index+1;
        self.currentTingId = [self.radiolist[self.index] playinfo].tingid;
        [self playRadio];
        dispatch_async(dispatch_get_main_queue(), ^{
        self.model = [self.radiolist[self.index] playinfo];
        [self loadDataOfPlayInfo];
        });
    });
}

//播放暂停
- (IBAction)playOrPause:(id)sender {
    
    [self changeplayState];
}

//改变状态
-(void)changeplayState{

    if ([self.playBtn.currentTitle isEqualToString:@"暂停"]) {
        _isPlay = NO;
        [self.playBtn setTitle:@"播放" forState:UIControlStateNormal];
        [[PlayManager shareManager] pauseRadio];
        [self closeTimer];
    }else if ([self.playBtn.currentTitle isEqualToString:@"播放"]){
        _isPlay = YES;
        [self.playBtn setTitle:@"暂停" forState:UIControlStateNormal];
        [[PlayManager shareManager] playRadio];
        [self startTimer];
    }
}

//下一首
- (IBAction)perRadio:(UIButton *)sender {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        self.index = self.index == 0?self.radiolist.count - 1:self.index-1;
        self.currentTingId = [self.radiolist[self.index] playinfo].tingid;
        [self playRadio];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.model = [self.radiolist[self.index] playinfo];
            [self loadDataOfPlayInfo];
        });
    });
}


//根据数据加载视图
-(void)loadDataOfPlayInfo{

    [self.coverimg sd_setImageWithURL:[NSURL URLWithString:self.model.imgUrl] placeholderImage:[UIImage imageNamed:@"IconProfile"]];
    [self.titleLable setText:self.model.title];
    NSURL* url = [NSURL URLWithString:self.model.webview_url];
    NSURLRequest* request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
    [self.tableView reloadData];
    [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:self.index inSection:0] animated:YES scrollPosition:UITableViewScrollPositionMiddle];
}

-(void)setVIews{
    [[self.coverimg layer] setMasksToBounds:YES];
    [[self.coverimg layer] setCornerRadius:self.coverimg.frame.size.width/2];
    [self.webView.scrollView setBounces:NO];
}

#pragma mark - tableViewdelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.radiolist.count;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RadioListTableViewCell* cell =[tableView dequeueReusableCellWithIdentifier:@"RadioListCell" forIndexPath:indexPath];
    cell.titleLable.text = [[self.radiolist objectAtIndex:indexPath.row] title];

    PlayInfoModel* playinfo = [[self.radiolist objectAtIndex:indexPath.row] playinfo];
    cell.authorname.text = playinfo.authorinfoModel.uname;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{


    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        self.index = indexPath.row;
        self.model = [self.radiolist[self.index] playinfo];

        [self playRadio];
        dispatch_async(dispatch_get_main_queue(), ^{


            [self loadDataOfPlayInfo];
        });
    });
}

#pragma mark - UIScrolleViewDeleagte
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{

    if (scrollView == self.scrollView) {
        CGPoint offset = scrollView.contentOffset;
        if (offset.x==0) {
            self.pagecontroller.currentPage = 0;
        }
        if (offset.x == kViewWidth) {
            self.pagecontroller.currentPage = 1;
        }
        if (offset.x == kViewWidth*2) {
            self.pagecontroller.currentPage = 2;
        }
    }
}

#pragma mark - playmanageDelegate
//播放器的代理方法
-(void)playManagerFetchRestTime:(NSString *)restTime progress:(CGFloat)progress{
//    NSLog(@"---%@",restTime);
    self.timeLable.text = restTime;
    self.downLoadPrograss.value = progress;
}

-(void)playManagerPlayRadioEnd{

    [self nextRadio:nil];
}

-(void)dealloc{

    [self closeTimer];
}


@end
